<template>
  <div class="card-body" :class="{ 'vertical-layout': collapsed }">
    <!-- 加载状态提示 -->
    <div v-if="isLoading" class="loading-container">
      <div class="loading-spinner">
        <i class="el-icon-loading is-spinning"></i>
      </div>
      <div class="loading-text">Load the comment data...</div>
    </div>

    <!-- 修改点：直接使用review对象，不循环 -->
    <template v-else>
      <div class="left-section">
        <div class="user-info">
          <div class="username">{{ review.userName }}</div>
          <div class="stay">
            <div class="stay-info" style="display: flex; align-items: center">
              Stay:

              <div class="data">{{ formatDate(review.checkInTime) }}</div>
            </div>
            <div class="stay-info">
              Review:
              <div class="data">{{ formatDate(review.reviewCreateTime) }}</div>
            </div>
          </div>
        </div>
        <div
          ref="reviewText"
          class="review-text"
          :style="{
            maxHeight: isExpanded ? 'none' : `${maxHeight}px`,
            overflow: isExpanded ? 'visible' : 'hidden',
            position: 'relative',
          }"
          style="white-space: pre-line"
        >
          <span>
            <template v-for="(segment, i) in getHighlightedSegments(review)">
              <span
                v-if="segment.highlighted"
                :key="'highlight-' + i"
                class="underlined"
                :style="{
                  'text-decoration-color': getCategoryColor(segment.category),
                }"
              >
                {{ formatText(segment.text) }}
              </span>
              <span v-else :key="'normal-' + i">
                {{ formatText(segment.text) }}</span
              >
            </template>
          </span>
        </div>
        <!-- 阅读更多按钮 -->
        <div
          v-if="contentExceedsMaxHeight"
          class="btn-container"
          style="display: flex; justify-content: center; gap: 20px"
        >
          <div
            v-if="!isExpanded"
            ref="readMoreBtn"
            class="read-more-btn"
            @click="toggleExpand"
          >
            <button
              style="
                border: none;
                background: #ccc;
                font-family: 'Inter Variable', sans-serif;
                font-size: 0.0972rem;
              "
            >
              Read More
            </button>
            <i class="el-icon-caret-bottom"></i>
          </div>
          <div
            v-else
            ref="showLessBtn"
            class="show-less-btn"
            @click="toggleExpand"
          >
            <button
              style="
                border: none;
                background: #ccc;
                font-family: 'Inter Variable', sans-serif;
                font-size: 0.0972rem;
              "
            >
              Show Less
            </button>
            <i class="el-icon-caret-top"></i>
          </div>
        </div>
      </div>

      <div class="right-section">
        <div>
          <HotelAspectScores
            :categories="review.sentimentAnalysis.categories || []"
          />
          <div class="summary">
            <p class="summary-title">Summary</p>
            <!-- <p class="summary-text positive-summary">
              {{ review.sentimentAnalysis.summary.positives }}
            </p>
            <p class="summary-text negative-summary">
              {{ review.sentimentAnalysis.summary.negatives }}
            </p> -->
            <!-- 正面评价 -->
            <div
              style="
                display: flex;
                align-items: flex-start;
                gap: 12px;
                margin-bottom: 8px;
              "
            >
              <!-- 关键：减少图片顶部间距，与文本第一行对齐 -->
              <img
                src="@/assets/pos.png"
                style="
                  width: 0.1389rem;
                  height: 0.1389rem;
                  margin-top: 3px;
                  margin-right: 0.0694rem;
                "
                alt="Positive"
              />
              <p
                style="
                  margin: 0;
                  padding: 0;
                  line-height: 1.5;
                  font-size: 0.1111rem;
                "
              >
                <!-- 确保文本行高与图片对齐 -->
                <span
                  style="
        background: #dbf4e2;
        padding: 2px 4px;  <!-- 增加左右内边距，视觉更协调 -->
        display: inline;
         box-decoration-break: clone; 
    -webkit-box-decoration-break: clone; 
      "
                >
                  {{ review.sentimentAnalysis.summary.positives }}
                </span>
              </p>
            </div>

            <!-- 负面评价 -->
            <div
              style="
                display: flex;
                align-items: flex-start;
                gap: 12px;
                margin-top: 20px;
              "
            >
              <img
                src="@/assets/neg.png"
                style="
                  width: 0.1389rem;
                  height: 0.1389rem;
                  margin-top: 3px;
                  margin-right: 0.0694rem;
                "
                alt="Negative"
              />
              <p
                style="
                  margin: 0;
                  padding: 0;
                  line-height: 1.5;
                  font-size: 0.1111rem;
                "
              >
                <span
                  style="
                    background: rgba(247, 11, 11, 0.08);
                    padding: 2px 4px;
                    display: inline;
                    box-decoration-break: clone;
                    -webkit-box-decoration-break: clone;
                  "
                >
                  {{ review.sentimentAnalysis.summary.negatives }}
                </span>
              </p>
            </div>
          </div>
        </div>
        <div class="action-buttons">
          <button
            class="btn reply"
            :class="{ active: isReplyExpanded }"
            @click="handleReplyClick"
          >
            {{ isReplyExpanded ? "Replied" : "Reply" }}
            <!-- 按钮文本同步状态 -->
          </button>
          <button class="btn save">Save</button>
          <button class="btn investigate">Investigate</button>
          <button class="btn forward">Forward</button>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import HotelAspectScores from "./HotelAspectScores.vue";

export default {
  components: {
    HotelAspectScores,
  },
  props: {
    collapsed: {
      type: Boolean,
      default: false,
    },
    review: {
      type: Object,
      required: true,
      default: () => ({}),
    },
    isReplyExpanded: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isLoading: false,
      isExpanded: false,
      contentExceedsMaxHeight: false,
      // replyActive: false,
      categoryColors: {
        "Location & Neighbourhood": "#1D6EB1",
        Cleanliness: "#3BD3DA",
        "Room Comfort": "#6D03A1",
        "Hotel Amenities & Atmosphere": "#ED34DE",
        "Food & Beverage": "#FF6F61",
        "Guest Experience & Service": "#AA7942",
        "Value for Money": "#EFB82C",
      },
      maxHeight: 350,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.checkContentHeight();
    });
  },
  methods: {
    checkContentHeight() {
      const element = this.$refs.reviewText;
      if (!element) return;

      // 临时移除高度限制以测量实际高度
      const originalMaxHeight = element.style.maxHeight;
      element.style.maxHeight = "none";

      const contentHeight = element.scrollHeight;
      this.contentExceedsMaxHeight = contentHeight > this.maxHeight;

      // 恢复样式
      element.style.maxHeight = originalMaxHeight;
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
      this.$nextTick(() => {
        this.checkContentHeight();
      });
    },
    handleReplyClick() {
      this.$emit("replyClick");
    },
    formatDate(date) {
      if (!date) return "Unknown";
      const d = new Date(date);
      const monthAbbr = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
      ];
      return `${monthAbbr[d.getMonth()]} ${d.getDate()}, ${d
        .getFullYear()
        .toString()}`;
    },
    getCategoryColor(categoryName) {
      return this.categoryColors[categoryName] || "#000000";
    },
    formatText(text) {
      if (!text) return "";
      let formatted = text.replace(/^\"|\"$/g, "");
      formatted = formatted.replace(/[ \t]+/g, " ");
      formatted = formatted.replace(/([!?,.;:])(\S|$)/g, "$1 $2");
      return formatted.replace(/^[ \t]+|[ \t]+$/g, "");
    },
    getHighlightedSegments(item) {
      if (!item?.content || !item?.sentimentAnalysis?.categories) {
        return [{ text: item.content || "", highlighted: false }];
      }

      const segments = [];
      const content = item.content;
      const categories = item.sentimentAnalysis.categories;

      const evidenceList = [];
      categories.forEach((category) => {
        category.evidence?.forEach((evidence) => {
          if (evidence?.trim()) {
            evidenceList.push({
              text: evidence.trim(),
              originalText: evidence,
              category: category.name,
            });
          }
        });
      });

      evidenceList.sort((a, b) => b.text.length - a.text.length);

      const matchedRanges = [];
      let lastPos = 0;
      const contentLower = content.toLowerCase();

      evidenceList.forEach((evidenceObj) => {
        const { text, originalText, category } = evidenceObj;
        const searchText = text.toLowerCase();
        let startIndex = 0;

        while (startIndex < content.length) {
          const index = contentLower.indexOf(searchText, startIndex);
          if (index === -1) break;

          const isOverlap = matchedRanges.some(
            (range) => index < range.end && index + text.length > range.start
          );

          if (!isOverlap) {
            matchedRanges.push({
              start: index,
              end: index + originalText.length,
              category: category,
            });
          }
          startIndex = index + text.length;
        }
      });

      matchedRanges.sort((a, b) => a.start - b.start);

      matchedRanges.forEach((range) => {
        if (range.start > lastPos) {
          segments.push({
            text: this.formatText(content.substring(lastPos, range.start)),
            highlighted: false,
          });
        }
        segments.push({
          text: this.formatText(content.substring(range.start, range.end)),
          highlighted: true,
          category: range.category,
        });
        lastPos = range.end;
      });

      if (lastPos < content.length) {
        segments.push({
          text: this.formatText(content.substring(lastPos)),
          highlighted: false,
        });
      }

      return segments.length > 0
        ? segments
        : [{ text: this.formatText(content), highlighted: false }];
    },
  },
};
</script>

<style scoped lang="scss">
/* 完全保持您原有的样式 */
.card-body {
  position: relative;
  padding: 24px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  gap: 24px;
  height: 100%;

  .left-section {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
  }
  .right-section {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  &.vertical-layout {
    flex-direction: column;
    padding: 24px;
    gap: 16px;

    .left-section {
      width: 100%;
    }

    .right-section {
      width: 100%;
    }
  }

  .left-section {
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
  }

  .user-info {
    .username {
      font-size: 0.125rem;
      font-weight: 700;
      color: #454545;
      margin-bottom: 12px;
    }
    .stay {
      display: flex;
      align-items: center !important;
      margin-bottom: 20px;
      .stay-info {
        display: flex;
        align-items: center !important;
        font-size: 0.1111rem;
        font-weight: 600;
        color: #0d4c80;
        margin-right: 24px;
        .data {
          font-size: 0.1111rem;
          font-weight: 400;
          color: #6a6969;
          margin-left: 8px;
        }
      }
    }
  }
  .review-text {
    font-family: "Inter Variable", sans-serif;
    font-size: 0.0972rem;
    font-weight: 400;
    color: #232323;
    line-height: 1.6;
    letter-spacing: 0.5px;
    overflow: hidden;
    white-space: pre-line;
    &:not(.expanded)::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: linear-gradient(
        to bottom,
        rgba(255, 255, 255, 0),
        rgba(255, 255, 255, 0.9) 80%
      );
      pointer-events: none;
    }
    .underlined {
      text-decoration: underline;
      text-decoration-thickness: 2px;
      text-underline-offset: 4px;
    }
  }
  .btn-container {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: auto; // 关键：自动填充上方空间，将按钮推到左侧区域底部
    padding-top: 8px; // 与上方文本保持距离
  }
  .read-more-btn {
    // position: absolute;
    // bottom: 30px;
    background: #ccc;
    color: #000;
    border-radius: 4px;
    border: none;
    padding: 3px;
    margin-top: 5px;
  }
  .show-less-btn {
    background: #ccc;
    color: #000;
    border-radius: 4px;
    border: none;
    padding: 3px;
    margin-top: 5px;
  }
  .action-buttons {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 16px;

    .btn {
      font-family: "Inter Variable", sans-serif;
      // padding: .0556rem .1111rem;
      padding: 8px 16px;
      border-radius: 4px;
      border: none;
      cursor: pointer;
      font-weight: 600;
      background: #0d4c80;
      font-size: 0.0972rem;
      color: #f5f2ea;
      transition: background-color 0.3s ease;
    }

    .btn.reply {
      /* 默认样式 */
    }

    .btn.reply.active {
      background-color: #d7eafd;
      color: #000;
    }
  }
  .summary {
    margin-bottom: 24px;
    .summary-title {
      font-weight: 600;
      font-size: 0.1111rem;
      color: #232323;
      margin-bottom: 8px;
    }
    .summary-text {
      color: #454545;
      font-size: 0.0972rem;
      font-weight: 400;
      font-family: "Inter Variable", sans-serif;
      padding: 2px 8px; /* 增加一点内边距让阴影更明显 */

      &.positive-summary {
        text-shadow: 0 0 6px rgba(47, 170, 104, 0.8),
          // 更强的绿色阴影
          0 0 12px rgba(47, 170, 104, 0.4); // 第二层扩散阴影
        // background-color: rgba(47, 170, 104, 0.1); // 轻微绿色背景增强效果
      }

      &.negative-summary {
        text-shadow: 0 0 6px rgba(206, 64, 73, 0.8),
          // 更强的红色阴影
          0 0 12px rgba(206, 64, 73, 0.4); // 第二层扩散阴影
        // background-color: rgba(206, 64, 73, 0.1); // 轻微红色背景增强效果
      }
    }
    .summary-title {
      font-weight: 600;
      font-size: 0.0972rem;
      color: #232323;
      margin-bottom: 8px;
    }
    .summary-text {
      color: #454545;
      font-size: 0.0972rem;
      font-weight: 400;
      font-family: "Inter Variable", sans-serif;
    }
  }
}
</style>
